<template>
  <div class="search-container">
    <!-- 搜索组件一级路由   $router.back()返回上一个页面-->
    <van-nav-bar left-arrow title="搜索中心" @click-left="$router.back()">
    </van-nav-bar>

    <!-- https://youzan.github.io/vant/#/zh-CN/search -->
    <van-search
      placeholder="请输入搜索关键词"
      shape="round"
      v-model.trim="keyword"
      @input="inputHandler"
      @search="toResult"
    >
      <template #action>
        <div>搜索</div>
      </template>
    </van-search>

    <!-- 联想建议 -->
    <van-cell-group>
      <van-cell
        v-for="(item, index) in hightlightOptions"
        :key="index"
        icon="search"
        @click="toResultWithQuery(index)"
      >
        <template #title>
          <div v-html="item"></div>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- /联想建议 -->
  </div>
</template>

<script>
import { getSearchSuggestion } from '../../api/search'
export default {
  name: 'search',
  data () {
    return {
      keyword: '', // 搜索关键字
      options: [],
      timeoutId: '',
      canSearch: true
    }
  },
  computed: {
    hightlightOptions () {
      const opts = this.options.map(v => {
        return v.replace(
          this.keyword,
          `<span style="color:red">${this.keyword}</span>`
        )
      })
      return opts
    }
  },
  methods: {
    toResult () {
      if (this.keyword === '') return this.$toast.fail('不能为空')
      this.$router.push({ path: '/result', query: { q: this.keyword } })
    },
    toResultWithQuery (index) {
      this.$router.push({ path: '/result', query: { q: this.options[index] } })
    },
    async inputHandler () {
      // 节流
      if (!this.keyword) {
        this.options = []
        return
      }
      if (this.canSearch === true) {
        this.canSearch = false
        const res = await getSearchSuggestion({ q: this.keyword })
        this.options = res.data.data.options
        this.timeoutId = setTimeout(() => {
          this.canSearch = true
        }, 500)
      }

      // 防抖
      // // 在判断外clear好点，不然进入else后面会报错
      // clearTimeout(this.timeoutId)
      // if (this.keyword) {
      //   this.timeoutId = setTimeout(async () => {
      //     const res = await getSearchSuggestion({ q: this.keyword })
      //     this.options = res.data.data.options
      //   }, 500)
      // } else {
      //   this.options = []
      // }
    }
  }
}
</script>

<style lang="less">
.search-container {
  .van-nav-bar {
    background-color: #3296fa;
    .van-nav-bar__title {
      color: white;
    }
    .van-icon {
      color: white;
    }
  }
}
</style>
